package com.stx.openeyes.view.activity;

import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.res.Configuration;
import android.media.AudioManager;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.OrientationEventListener;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import android.widget.AbsListView;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.facebook.drawee.backends.pipeline.Fresco;
import com.facebook.drawee.controller.AbstractDraweeController;
import com.facebook.drawee.view.SimpleDraweeView;
import com.facebook.imagepipeline.postprocessors.IterativeBoxBlurPostProcessor;
import com.facebook.imagepipeline.request.ImageRequest;
import com.facebook.imagepipeline.request.ImageRequestBuilder;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.jaeger.library.StatusBarUtil;
import com.shuyu.gsyvideoplayer.GSYVideoManager;
import com.shuyu.gsyvideoplayer.listener.GSYSampleCallBack;
import com.shuyu.gsyvideoplayer.listener.GSYVideoProgressListener;
import com.shuyu.gsyvideoplayer.model.VideoOptionModel;
import com.shuyu.gsyvideoplayer.utils.NetInfoModule;
import com.shuyu.gsyvideoplayer.utils.OrientationUtils;
import com.shuyu.gsyvideoplayer.video.StandardGSYVideoPlayer;
import com.stx.openeyes.MainActivity;
import com.stx.openeyes.R;
import com.stx.openeyes.SealConst;
import com.stx.openeyes.adapter.MyVideoItemAdapter;
import com.stx.openeyes.adapter.VideoRemarkAdapter;
import com.stx.openeyes.dto.Response;
import com.stx.openeyes.helper.VideoPlayerHelper;
import com.stx.openeyes.model.UserVideo;
import com.stx.openeyes.model.Video;
import com.stx.openeyes.model.VideoDetailDto;
import com.stx.openeyes.task.MyDownLoadAsyncTask;
import com.stx.openeyes.utils.ContextUtil;
import com.stx.openeyes.utils.HttpAdress;
import com.stx.openeyes.utils.NToast;
import com.stx.openeyes.utils.NetConnectedUtils;
import com.stx.openeyes.utils.ToastUtil;
import com.stx.openeyes.view.CoverVideoPlayerView;
import com.stx.openeyes.view.MNPasswordEditText;
import com.stx.openeyes.widget.ClearWriteEditText;
import com.stx.openeyes.widget.LoadDialog;
import com.zhy.http.okhttp.OkHttpUtils;
import com.zhy.http.okhttp.callback.StringCallback;

import java.lang.reflect.Field;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import okhttp3.Call;
import tv.danmaku.ijk.media.player.IjkMediaPlayer;

import static com.stx.openeyes.MainActivity.getContext;

/**
 * 视频详情activity
 */
public class VideoDetailActivity extends AppCompatActivity {

    // 试看百分比 0.1 = 10%
    private final double percent = 0.2;

    CoverVideoPlayerView videoPlayer;

    OrientationUtils orientationUtils;

    VideoDetailDto currentDto;

    UserVideo userVideo;

    private boolean isPlay = true;

    private Dialog dialog;
    private Dialog passwordDialog;
    private Dialog bottomDialog;
    private Dialog remarkDialog;
    private ClearWriteEditText pinglu;

    private boolean isPause;

    protected Context mContext;

    private Gson mGson;

    private Integer videoId;

    private Integer isBuy = 0;

    private Integer isRecommend = 0;

    private BigDecimal price = BigDecimal.ZERO;

    private String videoTitle;

    List<Video> listAll = new ArrayList<Video>();

    List<UserVideo> listRemark = new ArrayList<UserVideo>();

    @BindView(R.id.video_detail_ivmo)
    SimpleDraweeView videoDetailIvmo;

    @BindView(R.id.video_detail_item_listview)
    ListView lvHome;

    @BindView(R.id.video_detail_title)
    TextView videoDetailTitle;

    @BindView(R.id.video_detail_time)
    TextView videoDetailTime;

    @BindView(R.id.video_detail_vip)
    TextView videoDetailVip;

    @BindView(R.id.video_detail_desc)
    TextView videoDetailDesc;

    @BindView(R.id.video_detail_iv_fav)
    ImageView videoDetailIvFav;

    @BindView(R.id.tv_download)
    ImageView tvDownload;

    @BindView(R.id.cv_video_desc)
    LinearLayout linearLayoutDesc;

    @BindView(R.id.video_detail_view_line)
    View videoDetailViewLine;

    @BindView(R.id.cv_video_tag)
    LinearLayout linearLayoutTag;

    @BindView((R.id.pinglun))
    ImageView remarkview;



    private MyVideoItemAdapter mAdapter;

    private VideoRemarkAdapter mAdapter2;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mContext = this;

        //set no title bar 需要在setContentView之前调用
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        //如果上面的不起作用，可以换成下面的。
        if (getSupportActionBar() != null) getSupportActionBar().hide();
        if (getActionBar() != null) getActionBar().hide();
        //no status bar
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
        setContentView(R.layout.player_activity_video_player);
        videoPlayer = (CoverVideoPlayerView) findViewById(R.id.cv_video_view);
        ButterKnife.bind(this);
        initView();
    }

    private void initView() {
        listAll.clear();
        LoadDialog.show(mContext);
        if (videoId == null)
            videoId = getIntent().getIntExtra("id", 0);
        OkHttpUtils.get()
                .url(String.format(HttpAdress.VIDEO_DETAIL, videoId))
                .addHeader("deviceId", ContextUtil.getDevicedId())
                .addHeader("token", ContextUtil.getCurrentUserToken())
                .build()
                .execute(new StringCallback() {
                    @Override
                    public void onError(Call call, Exception e, int id) {
                        Log.i("===error", e.getMessage());
                        LoadDialog.dismiss(mContext);
                        NToast.shortToast(mContext, SealConst.NETWORK_ERROR);
                    }

                    @Override
                    public void onResponse(String response, int id) {
                        Log.i("===json", response);
                        mGson = new Gson();
                        Response<VideoDetailDto> videoResponse = mGson.fromJson(response,
                                new TypeToken<Response<VideoDetailDto>>() {
                                }.getType());
                        if (!videoResponse.isSuccess()) {
                            NToast.shortToast(mContext, videoResponse.getMessage());
                            LoadDialog.dismiss(mContext);
                            return;
                        }
                        VideoDetailDto detailDto = videoResponse.getData();
                        listAll.addAll(detailDto.getRecommendVideos());
                        myNotify();
                        initDetailView(detailDto);
                        initVideoView(detailDto);
                        setLvAdapter();
                        LoadDialog.dismiss(mContext);
                    }
                });
    }

    private void initView2() {
        listRemark.clear();
        OkHttpUtils.get()
                .url(String.format(HttpAdress.VIDEO_REMARK))
                .addParams("id", currentDto.getId().toString())
                .addHeader("deviceId", ContextUtil.getDevicedId())
                .addHeader("token", ContextUtil.getCurrentUserToken())
                .build()
                .execute(new StringCallback() {
                    @Override
                    public void onError(Call call, Exception e, int id) {
                        Log.i("===error", e.getMessage());
                        LoadDialog.dismiss(mContext);
                        NToast.shortToast(mContext, "chuanbuguolai");
                    }

                    @Override
                    public void onResponse(String response, int id) {
                        Log.i("===json", response);
                        mGson = new Gson();
                        Response<List<UserVideo>> videoResponse = mGson.fromJson(response,
                                new TypeToken<Response<List<UserVideo>>>() {
                                }.getType());
                        if (!videoResponse.isSuccess()) {
                            NToast.shortToast(mContext, videoResponse.getMessage());
                            LoadDialog.dismiss(mContext);
                            return;
                        }
                        listRemark.addAll(videoResponse.getData());
                        myNotify2();


                    }
                });
    }

    public void myNotify() {
        if (mAdapter != null) {
            mAdapter.notifyDataSetChanged();
        }
    }

    public void myNotify2() {
        if (mAdapter2 != null) {
            mAdapter2.notifyDataSetChanged();
        }
    }

    private void setLvAdapter() {
        mAdapter = new MyVideoItemAdapter(mContext, listAll);
        lvHome.setAdapter(mAdapter);
    }




    private void initDetailView(VideoDetailDto detailDto) {
        currentDto = detailDto;
        // 高斯模糊
        try {
            Uri uri = Uri.parse(detailDto.getPreviewImg());
            ImageRequest request = ImageRequestBuilder.newBuilderWithSource(uri)
                    .setPostprocessor(new IterativeBoxBlurPostProcessor(6, 15))
                    .build();
            AbstractDraweeController controller = Fresco.newDraweeControllerBuilder()
                    .setOldController(videoDetailIvmo.getController())
                    .setImageRequest(request)
                    .build();
            videoDetailIvmo.setController(controller);
        } catch (Exception e) {
            e.printStackTrace();
        }
        videoDetailTitle.setText(detailDto.getTitle());
        videoDetailTime.setText(detailDto.getTagStr());
        videoDetailDesc.setText(detailDto.getDescription());
        price = detailDto.getPrice();
        isBuy = detailDto.getIsBuy();
        videoTitle = detailDto.getTitle();
        isRecommend = detailDto.getIsRecommend();
        // 如果是免费视频，不显示购买按钮 状态: {0: 普通, 1: 付费}
        if (1 == detailDto.getType()) {
            videoDetailVip.setVisibility(View.VISIBLE);
        } else {
            isBuy = 1;
        }
        restOperationIcon();

        videoDetailVip.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                // 已购买不能继续操作
                if (isBuy != 0)
                    return;

                payDialog(true);
            }
        });

        videoDetailIvFav.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                collect(2);
            }
        });

        // 视频下载
        tvDownload.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                // 校验视频是否已在下载队列中
                SharedPreferences settings = getSharedPreferences(SealConst.DOWNLOAN_VIDEOS, 0);
                String infos = settings.getString(SealConst.DOWNLOAN_VIDEO_INFO, null);

                Log.i("download_video", infos + "");
                List<Video> videoList  = mGson.fromJson(infos, new TypeToken<List<Video>>() {
                        }.getType());
                if (checkIsExistDownloadList(videoList)) {
                    SharedPreferences.Editor editor = settings.edit();
                    if (videoList == null)
                        videoList = new ArrayList<>();
                    Video video = currentDto;
                    video.setIsDownloan(1);
                    videoList.add(video);
                    editor.putString(SealConst.DOWNLOAN_VIDEO_INFO, mGson.toJson(videoList));
                    editor.commit();
                    NToast.shortToast(mContext, "正在下载中......");
                    MyDownLoadAsyncTask myDownLoadAsyncTask = new MyDownLoadAsyncTask(mContext, video.getUrl());
                    myDownLoadAsyncTask.execute(500);
                } else {
                    NToast.shortToast(mContext, "该视频已在下载队列中");
                }
            }
        });

        //评论
        remarkview.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                remarkDialog();
            }
        });

        lvHome.setOnScrollListener(new AbsListView.OnScrollListener() {
            @Override
            public void onScrollStateChanged(AbsListView view, int scrollState) {
                switch (scrollState) {
                    case AbsListView.OnScrollListener.SCROLL_STATE_IDLE:
                        // 判断滚动到顶部
                        if (lvHome.getFirstVisiblePosition() == 0) {
                            linearLayoutDesc.setVisibility(View.VISIBLE);
                            linearLayoutTag.setVisibility(View.VISIBLE);
                            videoDetailViewLine.setVisibility(View.VISIBLE);
                        }
                        if (lvHome.getFirstVisiblePosition() != 0) {
                            linearLayoutDesc.setVisibility(View.GONE);
                            linearLayoutTag.setVisibility(View.GONE);
                            videoDetailViewLine.setVisibility(View.GONE);
                        }
                        break;

                    case SCROLL_STATE_TOUCH_SCROLL:

                        break;

                    case SCROLL_STATE_FLING:
                        break;
                }
            }

            @Override
            public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {
                //Toast.makeText(mContext, "" + firstVisibleItem, Toast.LENGTH_SHORT).show();
            }
        });
        lvHome.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                Video data = listAll.get(position);
                videoId = data.getId();
                initView();
            }
        });
    }

    private boolean checkIsExistDownloadList(List<Video> videos) {
        if (videos == null || videos.size() == 0)
            return true;

        for (Video video : videos) {
            if (video.getId().equals(currentDto.getId())) {
                return false;
            }
        }
        return true;
    }

    private void restOperationIcon() {
        if (isBuy != 0) {
            // 设置按钮不能点击
            videoDetailVip.setClickable(false);
            videoDetailVip.setText("  #已购买");
        }
        if (isRecommend != 0) {
            videoDetailIvFav.setImageResource(R.drawable.ic_action_favorites_added_without_padding);
        } else {
            videoDetailIvFav.setImageResource(R.drawable.ic_action_favorites_without_padding);
        }
    }

    private void initVideoView(VideoDetailDto detailDto) {
        // 设置返回键
        videoPlayer.getBackButton()
                .setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        finish();
                    }
                });
        // 全屏辅助
        orientationUtils = new OrientationUtils(this, videoPlayer);
        // 初始化不打开外部的旋转
        orientationUtils.setEnable(false);
        // 初始化配置
        VideoPlayerHelper.optionPlayer(videoPlayer,
                detailDto.getUrl(),
                false, // 暂时不缓存
                detailDto.getTitle());

        // VideoPlayerHelper.clonePlayState(viewDataBinding.cvVideoView);

        videoPlayer.setIsTouchWiget(true);

        videoPlayer.setVideoAllCallBack(new GSYSampleCallBack() {
            @Override
            public void onPrepared(String url, Object... objects) {
                super.onPrepared(url, objects);
                // 开始播放了才能旋转和全屏
                orientationUtils.setEnable(true);
            }

            @Override
            public void onQuitFullscreen(String url, Object... objects) {
                super.onQuitFullscreen(url, objects);
                if (orientationUtils != null) {
                    orientationUtils.backToProtVideo();
                }
            }
        });

        videoPlayer.setGSYVideoProgressListener(new GSYVideoProgressListener() {
            @Override
            public void onProgress(int progress, int secProgress, int currentPosition, int duration) {
                // 如果是收费视频，只能播放20%，交费后可继续收看
                if (currentPosition >= duration * percent && isBuy == 0) {
                    // 暂停播放
                    videoPlayer.seekTo((long) (duration * percent));
                    videoPlayer.getCurrentPlayer().onVideoPause();
                    Log.i("---progress", "当前播放进度：" + progress + "，当前播放位置：" + currentPosition + "，总时长：" + duration);
                    //Log.i("---progress", "退出了全屏" + videoPlayer.backFromFull(mContext));
                    payDialog(false);
                }
            }
        });
        videoPlayer.startPlayLogic();
    }

    @Override
    public void onBackPressed() {
        if (orientationUtils != null) {
            orientationUtils.backToProtVideo();
        }
        if (GSYVideoManager.backFromWindowFull(this)) {
            return;
        }
        super.onBackPressed();
    }

    @Override
    protected void onPause() {
        videoPlayer.getCurrentPlayer().onVideoPause();
        super.onPause();
        isPause = true;
    }

    @Override
    protected void onResume() {
//        videoPlayer.getCurrentPlayer().onVideoResume(false);
        super.onResume();
        isPause = false;
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        videoPlayer.getGSYVideoManager()
                .setListener(videoPlayer.getGSYVideoManager()
                        .lastListener());
        videoPlayer.getGSYVideoManager().setLastListener(null);
        videoPlayer.clearCurrentCache();
        videoPlayer.cancel();

        videoPlayer.getCurrentPlayer().release();

        GSYVideoManager.releaseAllVideos();

        if (orientationUtils != null) {
            orientationUtils.releaseListener();
            try {
                // 第三方库中的内存泄漏,只能利用反射来解决
                Field mOrientationEventListener = OrientationUtils.class
                        .getDeclaredField("mOrientationEventListener");
                Field contextField =
                        OrientationUtils.class.getField("mActivity");
                contextField.setAccessible(true);
                contextField.set(orientationUtils, null);
                mOrientationEventListener.setAccessible(true);
                OrientationEventListener listener =
                        (OrientationEventListener) mOrientationEventListener
                                .get(orientationUtils);
                Field mSensorEventListener = OrientationEventListener.class
                        .getDeclaredField("mSensorEventListener");
                mSensorEventListener.setAccessible(true);
                mSensorEventListener.set(listener, null);
                Field mSensorManager = OrientationEventListener.class
                        .getDeclaredField("mSensorManager");
                mSensorManager.setAccessible(true);
                mSensorManager.set(listener, null);

            } catch (NoSuchFieldException e) {
                e.printStackTrace();
            } catch (IllegalAccessException e) {
                e.printStackTrace();
            }
            orientationUtils = null;
        }
        VideoPlayerHelper.release();
    }

    @Override
    public void onConfigurationChanged(Configuration newConfig) {
        super.onConfigurationChanged(newConfig);
        // 如果旋转了就全屏
        if (isPlay && !isPause) {
            videoPlayer.onConfigurationChanged(this,
                    newConfig,
                    orientationUtils,
                    true,
                    true);
        }
    }

    private void payDialog(boolean initiative) {
        videoPlayer.getCurrentPlayer().onVideoPause();
        AlertDialog.Builder builder = new AlertDialog.Builder(mContext);

        View view = LayoutInflater.from(mContext).inflate(R.layout.layout_dialog_pay, null, false);
        // 将view添加到builder中
        builder.setView(view);
        // 创建dialog
        dialog = builder.create();

        Button confirm = (Button) view.findViewById(R.id.dialog_confirm);
        Button cancel = (Button) view.findViewById(R.id.dialog_cancel);
        TextView priceTv = (TextView) view.findViewById(R.id.dialog_price);
        TextView msgTv = (TextView) view.findViewById(R.id.dialog_msg);
        // 主动购买不需要显示试看结束
        if (initiative)
            msgTv.setVisibility(View.GONE);
        priceTv.setText("本视频价格为" + price + "元，请支付：");

        // 确认按钮
        confirm.setOnClickListener(new android.view.View.OnClickListener() {
            @Override
            public void onClick(View arg0) {
                //payPasswordDialog();
                cashierDialog(initiative);
            }
        });

        // 取消按钮
        cancel.setOnClickListener(new android.view.View.OnClickListener() {
            @Override
            public void onClick(View arg0) {
                if (!initiative)
                    finish();
                else {
                    videoPlayer.getCurrentPlayer().onVideoResume();
                    dialog.dismiss();
                }
            }
        });
        if (!initiative)
            dialog.setCancelable(false);
        dialog.show();
    }

    private void cashierDialog(boolean initiative) {
        dialog.dismiss();
        bottomDialog = new Dialog(this, R.style.BottomDialog);
        View contentView = LayoutInflater.from(this).inflate(R.layout.layout_dialog_cashier, null);
        bottomDialog.setContentView(contentView);
        ViewGroup.LayoutParams layoutParams = contentView.getLayoutParams();
        layoutParams.width = getResources().getDisplayMetrics().widthPixels;
        contentView.setLayoutParams(layoutParams);
        bottomDialog.getWindow().setGravity(Gravity.BOTTOM);
        bottomDialog.setCanceledOnTouchOutside(true);
        bottomDialog.getWindow().setWindowAnimations(R.style.BottomDialog_Animation);

        TextView dialogClose = (TextView) contentView.findViewById(R.id.dialog_close);
        TextView videoTitleTv = (TextView) contentView.findViewById(R.id.video_title_tv);
        TextView videoPrice1Tv = (TextView) contentView.findViewById(R.id.video_price1_tv);
        TextView videoPrice2Tv = (TextView) contentView.findViewById(R.id.video_price2_tv);
        TextView gotoPayTv = (TextView) contentView.findViewById(R.id.goto_pay_tv);
        videoTitleTv.setText(videoTitle);
        videoPrice1Tv.setText(price + "元");
        videoPrice2Tv.setText(price.toString());
        // 关闭按钮
        dialogClose.setOnClickListener(new android.view.View.OnClickListener() {
            @Override
            public void onClick(View arg0) {
                bottomDialog.dismiss();
                if (!initiative) {
                    // 打开试看结束提醒
                    payDialog(initiative);
                } else {
                    videoPlayer.getCurrentPlayer().onVideoResume();
                }
            }
        });
        // 去支付
        gotoPayTv.setOnClickListener(new android.view.View.OnClickListener() {
            @Override
            public void onClick(View arg0) {
                payPasswordDialog();
            }
        });
        bottomDialog.show();
    }

    private void payPasswordDialog() {
        AlertDialog.Builder builder = new AlertDialog.Builder(mContext);
        View view = LayoutInflater.from(mContext).inflate(R.layout.layout_dialog_password, null, false);
        MNPasswordEditText payPasswordEditText = (MNPasswordEditText) view.findViewById(R.id.mPswEditText);
        TextView closeTv = (TextView) view.findViewById(R.id.dialog_close);
        TextView priceTv = (TextView) view.findViewById(R.id.dialog_price);
        priceTv.setText("￥" + price);
        closeTv.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                passwordDialog.dismiss();
            }
        });
        payPasswordEditText.setOnTextChangeListener(new MNPasswordEditText.OnTextChangeListener() {
            @Override
            public void onTextChange(String text, boolean isComplete) {
                if (isComplete) {
                    // 调用购买接口，购买成功，关闭对话框，继续播放
                    collect(3);
                    passwordDialog.dismiss();
                }
            }
        });

        // 将view添加到builder中
        builder.setView(view);
        // 创建dialog
        passwordDialog = builder.create();

        passwordDialog.show();
        Timer timer = new Timer();
        timer.schedule(new TimerTask() {
            @Override
            public void run() {
                handler.sendEmptyMessage(0);
            }
        }, 200);
    }

    private void remarkDialog(){
        remarkDialog = new Dialog(this, R.style.BottomDialog);
        View contentView = LayoutInflater.from(this).inflate(R.layout.layout_dialog_remark, null);
        remarkDialog.setContentView(contentView);
        ViewGroup.LayoutParams layoutParams = contentView.getLayoutParams();
        layoutParams.width = getResources().getDisplayMetrics().widthPixels;
        contentView.setLayoutParams(layoutParams);
        remarkDialog.getWindow().setGravity(Gravity.BOTTOM);
        remarkDialog.setCanceledOnTouchOutside(true);
        remarkDialog.getWindow().setWindowAnimations(R.style.BottomDialog_Animation);

        TextView close = contentView.findViewById(R.id.remarkdialog_close);
        pinglu = contentView.findViewById(R.id.user_remark);
        TextView gotoremark =  contentView.findViewById(R.id.goto_remark);
        ListView lvremark = contentView.findViewById(R.id.remark_listview);

        close.setOnClickListener(new android.view.View.OnClickListener() {
            @Override
            public void onClick(View arg0) {
                remarkDialog.dismiss();
                videoPlayer.getCurrentPlayer().onVideoResume();
            }
        });

        gotoremark.setOnClickListener(new android.view.View.OnClickListener() {
            @Override
            public void onClick(View arg0) {
                collect(4);
            }
        });
        initView2();
        mAdapter2 = new VideoRemarkAdapter(this, listRemark);
        lvremark.setAdapter(mAdapter2);
        remarkDialog.show();

    }

    private void collect(Integer type) {
        LoadDialog.show(mContext);
        if(type != 4) {
            OkHttpUtils.post()
                    .url(HttpAdress.VIDEO_COLLECT)
                    .addParams("id", currentDto.getId().toString())
                    .addParams("type", type.toString())
                    .addHeader("deviceId", ContextUtil.getDevicedId())
                    .addHeader("token", ContextUtil.getCurrentUserToken())
                    .build()
                    .execute(new StringCallback() {
                        @Override
                        public void onError(Call call, Exception e, int id) {
                            Log.i("===error", e.getMessage());
                            NToast.shortToast(mContext, SealConst.NETWORK_ERROR);
                            LoadDialog.dismiss(mContext);
                        }

                        @Override
                        public void onResponse(String response, int id) {
                            Log.i("===json", response);
                            mGson = new Gson();
                            Response resp = mGson.fromJson(response, new TypeToken<Response>() {
                            }.getType());
                            if (!resp.isSuccess()) {
                                NToast.shortToast(mContext, resp.getMessage());
                                LoadDialog.dismiss(mContext);
                                return;
                            }
                            if (type == 3) { // 购买
                                isBuy = 1;
                                NToast.shortToast(mContext, SealConst.PAY_SUCCESSFUL);
                                videoPlayer.getCurrentPlayer().onVideoResume();
                                passwordDialog.dismiss();
                                //dialog.dismiss();
                                bottomDialog.dismiss();
                            }
                            if (type == 2) { // 收藏
                                if (isRecommend == 0) isRecommend = 1;
                                else isRecommend = 0;
                            }

                            restOperationIcon();
                            LoadDialog.dismiss(mContext);
                        }
                    });
        }

        if(type == 4){
            OkHttpUtils.post()
                    .url(HttpAdress.VIDEO_COLLECT)
                    .addParams("id", currentDto.getId().toString())
                    .addParams("type", type.toString())
                    .addParams("beizhu",pinglu.getText().toString())
                    .addHeader("deviceId", ContextUtil.getDevicedId())
                    .addHeader("token", ContextUtil.getCurrentUserToken())
                    .build()
                    .execute(new StringCallback() {
                        @Override
                        public void onError(Call call, Exception e, int id) {
                            Log.i("===error", e.getMessage());
                            NToast.shortToast(mContext, SealConst.NETWORK_ERROR);
                            LoadDialog.dismiss(mContext);
                        }

                        @Override
                        public void onResponse(String response, int id) {
                            Log.i("===json", response);
                            mGson = new Gson();
                            Response resp = mGson.fromJson(response, new TypeToken<Response>() {
                            }.getType());
                            if (!resp.isSuccess()) {
                                NToast.shortToast(mContext, resp.getMessage());
                                LoadDialog.dismiss(mContext);
                                return;
                            }

                            if(type ==4){  //评论
                                NToast.shortToast(mContext, SealConst.REMARK_SUCCESSFUL);
                                remarkDialog.dismiss();
                            }
                            restOperationIcon();
                            LoadDialog.dismiss(mContext);
                        }
                    });
        }
    }

    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            InputMethodManager inputMethodManager = (InputMethodManager) passwordDialog.getContext().getSystemService(Context.INPUT_METHOD_SERVICE);
            inputMethodManager.toggleSoftInput(0, InputMethodManager.HIDE_NOT_ALWAYS);
        }

    };
}
